<template>
  <view class="product-detail-page">
    <!-- 产品图片轮播 -->
    <view class="product-images">
      <swiper 
        class="image-swiper" 
        indicator-dots 
        indicator-color="rgba(255,255,255,0.5)"
        indicator-active-color="#ffffff"
        autoplay
        circular
        ref="swiper"
      >
        <swiper-item v-for="(img, index) in images" :key="index">
          <image 
            :src="img" 
            mode="widthFix" 
            class="product-img"
            @click="previewImage(index)"
          ></image>
        </swiper-item>
      </swiper>
      
      <!-- 轮播图计数器 -->
      <view class="image-counter">
        <text>{{ currentImageIndex + 1 }}/{{ imagesLength}}</text>
      </view>
    </view>
    
    <!-- 产品基本信息 -->
    <view class="product-base-info">
      <view class="product-title">{{ product.title }}</view>
      
      <view class="product-price">
        <text class="price-symbol">¥</text>
        <text class="price-value">{{ product.price }}</text>
        <text class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
        <text class="views-count">浏览 {{ product.views }} 次</text>
      </view>
      
      <!-- 新增：热力值显示 -->
      <view class="product-heat">
        <view class="heat-value">
          <u-icon name="heart-fill" size="24" color="#ff7a45"></u-icon>
          <text class="heat-text">热力值: {{ product.heatValue || 0 }}</text>
		  <!-- 提示图标：点击弹出提示框 -->
		  <view class="heat-tooltip" @click="showHeatModal">
		    <u-icon name="question-circle" size="22" color="#999"></u-icon>
		  </view>
        </view>        
		
        <button class="recharge-btn" @click="showRechargeModal" >
          打赏热力
        </button>
		
      </view>
	  <u-modal :show="showHeat" :title="title" :content='content' @confirm='confirm' :closeOnClickOverlay="true"></u-modal>
      <!-- 新增：热力值充值弹框 -->
          <u-modal 
            v-model="showRecharge" 
            title="充值热力值" 
			:show="showRecharge"
            :show-confirm-button="true"
            :show-cancel-button="true"
            confirm-text="确认充值"
            cancel-text="取消"
            @confirm="confirmRecharge"
            @cancel="showRecharge = false"
            :mask-close-able="true"
          >
            <view class="recharge-modal-content">
              <text class="recharge-desc">请输入充值数量（1积分/点）</text>
              <!-- 仅允许输入数字的输入框 -->
              <u--input 
                      v-model="rechargeAmount" 
                      type="number" 
                      class="recharge-input"
                      @input="handleAmountInput"
                      placeholder="请输入数字"
                      
                    />
              <view class="points-info" v-if="userPoints !== null">
                <text>当前可用积分：{{ userPoints }}</text>
              </view>
            </view>
          </u-modal>
      <view class="product-tags">
        <view class="tag" v-for="(tag, index) in product.tags" :key="index" :style="{ backgroundColor: tag.color }">
          {{ tag.text }}
        </view>
      </view>
      
      <view class="product-stock">
        <text>库存: {{ product.stock }} 件</text>
      </view>
    </view>
    
    <!-- 产品详情导航 -->
    <view class="detail-tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'detail' }"
        @click="activeTab = 'detail'"
      >
        产品详情
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'parameters' }"
        @click="activeTab = 'parameters'"
      >
        规格参数
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'seller' }"
        @click="activeTab = 'seller'"
      >
        商家信息
      </view>
    </view>
    
    <!-- 产品详情内容 -->
    <scroll-view class="detail-content" scroll-y="true">
      <!-- 产品详情 -->
      <view v-if="activeTab === 'detail'">
        <view class="detail-section">
          <view class="detail-desc">
            <text>{{ product.description }}</text>
          </view>
          
          <view class="detail-images">
            <image 
              :src="img" 
              mode="widthFix" 
              class="detail-img" 
              v-for="(img, index) in product.detailImages" 
              :key="index"
            ></image>
          </view>
        </view>
      </view>
      
      <!-- 规格参数 -->
      <view v-if="activeTab === 'parameters'">
        <view class="parameters-section">
          <view class="param-item" v-for="(param, index) in product.parameters" :key="index">
            <view class="param-name">{{ param.name }}</view>
            <view class="param-value">{{ param.value }}</view>
          </view>
        </view>
      </view>
      
      <!-- 商家信息 -->
      <view v-if="activeTab === 'seller'">
        <view class="seller-section">
          <view class="seller-header">
            <image :src="product.seller.avatar" mode="widthFix" class="seller-avatar"></image>
            <view class="seller-info">
              <view class="seller-name">{{ product.seller.userName }}</view>
              <!-- <view class="seller-rating">
                <view class="stars">
                  <u-icon name="star" size="16" color="#FFD700" v-for="n in 5" :key="n" :class="{ empty: n > product.seller.rating }"></u-icon>
                </view>
                <view class="rating-text">{{ product.seller.rating }} ({{ product.seller.ratingCount }}条评价)</view>
              </view> -->
            </view>
            <button class="contact-btn" @click="contactSeller">
              <u-icon name="phone" size="16" color="#ffffff"></u-icon>
              <text>联系商家</text>
            </button>
          </view>
          
          <view class="seller-contact">
            <view class="contact-item">
              <view class="contact-label">电话:</view>
              <view class="contact-value">{{ product.seller.phoneNumber}}</view>
            </view>
            <view class="contact-item">
              <view class="contact-label">地址:</view>
              <view class="contact-value">{{ product.seller.address }}</view>
            </view>
           <!-- <view class="contact-item">
              <view class="contact-label">营业时间:</view>
              <view class="contact-value">{{ product.seller.businessHours }}</view>
            </view> -->
          </view>
          
          <view class="seller-goods">
            <view class="seller-goods-title">店铺其他产品</view>
            <view class="other-goods">
              <view class="other-good" v-for="(good, index) in product.seller.otherProducts" :key="index">
                <image :src="good.image" mode="widthFix" class="other-good-img"></image>
                <view class="other-good-name">{{ good.name }}</view>
                <view class="other-good-price">¥{{ good.price.toFixed(2) }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'detail',
      // 当前显示的图片索引
      currentImageIndex: 0,
      // 产品数据
      product: {},
      // 用户积分
      userPoints: 0,
	  images:[],
	  imagesLength:0,
	  showHeat:false,
	  title:'热力说明',
	  content:'热力越高，产品搜索结果越靠前。用户打赏一个热力扣除一个积分。热力每日零点过后会减1，直到为0',
	  // 新增：充值相关变量
	  showRecharge: false, // 控制充值弹框显示
	  rechargeAmount: 1 // 充值数量，默认1      
    };
  },
  computed:{
  	...mapState(['userInfo', "appProperties"]),
  },
  onLoad(options) {
    if (options.id) {
	  const imagesStr = decodeURIComponent(options.images);  // 解码
	  this.images = JSON.parse(imagesStr);  // 解析 JSON 字符串
	  this.imagesLength =this.images.length
      this.fetchProductDetail(options.id);
      this.incrementViewCount(options.id);
      this.fetchUserPoints(); // 获取用户积分
    }
  },
  
  methods: {
	
	showRechargeModal(){
		if(!this.userInfo){
			uni.navigateTo({
			  url: `/pages/login/login`
			});
				return
		}  
	    this.showRecharge = true	
	},  
	// 新增：处理充值数量输入（仅允许正整数）
	handleAmountInput(value) {
	      // 过滤非数字字符，仅保留正整数
	      let filteredValue = value.replace(/[^\d]/g, '');
	      // 确保值不小于1
	      this.rechargeAmount = filteredValue ? Math.max(1, parseInt(filteredValue)) : 1;
	    }, 
	// 新增：确认充值
	confirmRecharge() {	
	  const amount = this.rechargeAmount;
	  
	  // 校验积分是否充足
	  if (this.userPoints === null) {
	    uni.showToast({ title: '获取积分信息失败', icon: 'none' });
	    return;
	  }
	  
	  if (amount > this.userPoints) {
	    uni.showToast({ title: '积分不足，无法充值', icon: 'none' });
	    return;
	  }
	  
	  // 调用充值接口
	  this.$request(`api/v1/rechargeHeat`, 'post',{
        heatChargeNum: this.rechargeAmount,id:this.product.id,userId:this.userInfo.appUserId
      }).then(res => {
	    if (res.code==200) {
	      // 更新产品热力值
	      this.product.heatValue = (this.product.heatValue || 0) + amount;
	      // 更新用户积分
	      this.userPoints -= amount;
	      // 提示成功
	      uni.showToast({ title: `成功充值${amount}点热力值`, icon: 'none' });
	      // 关闭弹框
	      this.showRecharge = false;
	      // 重置充值数量
	      this.rechargeAmount = 1;
	    } else {
	      uni.showToast({ title: res.message || '充值失败', icon: 'none' });
	    }
	  }).catch(err => {
	    console.error('充值失败', err);
	    uni.showToast({ title: '网络错误，充值失败', icon: 'none' });
	  });
	  this.showRecharge = false;
	},          
	confirm() {
	  this.showHeat = false;
	}, 
	showHeatModal(){
		console.log("jinlaile")
	  this.showHeat = true		  
	},  
    // 预览图片
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.product.images
      });
    },
    
    // 联系商家
    contactSeller() {
      uni.makePhoneCall({
        phoneNumber: this.product.seller.phoneNumber || '',
        fail: (err) => {
          console.error('拨打电话失败:', err);
          uni.showToast({
            title: '无法拨打电话',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    
    // 从接口获取产品详情
    fetchProductDetail(productId) {
      this.$request(`api/v1/productDetail/${productId}`,"GET").then(res => {
        if (res.code==200) {
          this.product = res.data;
        }
      }).catch(err => {
        console.error('获取产品详情失败:', err);
      });
    },
    
    // 增加浏览量
    incrementViewCount(productId) {
		this.$request(`api/v1/${productId}/productView`, 'POST').then(result => {
			if (result.code==200) {
				console.log(result.data)
			}   
		}).catch(err => {
        console.error('增加浏览量失败:', err);
      });  

    },
    
    // 获取用户积分
    fetchUserPoints() {
		if(this.userInfo){
			this.$request(`api/v1/userInfo/${this.userInfo.appUserId}`,'get').then(res => {
			  if (res.code==200) {
			    this.userPoints = res.data.integral;
			  }
			}).catch(err => {
			  console.error('获取用户积分失败:', err);
			});
		}
      
    },
  },
  
  watch: {
    // 监听轮播图变化，更新当前图片索引
    '$refs.swiper.current'(val) {
      this.currentImageIndex = val;
    }
  }
};
</script>

<style lang="scss" scoped>
.product-detail-page {
  background-color: #f5f5f7;
  min-height: 100vh;
}

// 产品图片轮播
.product-images {
  position: relative;
  
  .image-swiper {
    width: 100%;
    height: 500rpx;
  }
  
  .product-img {
    width: 100%;
    height: 100%;
  }
  
  .image-counter {
    position: absolute;
    bottom: 15rpx;
    right: 15rpx;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    font-size: 24rpx;
    padding: 5rpx 10rpx;
    border-radius: 4rpx;
  }
}

// 产品基本信息
.product-base-info {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 15rpx;
  
  .product-title {
    font-size: 34rpx;
    color: #333;
    line-height: 1.4;
    margin-bottom: 20rpx;
  }
  
  .product-price {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .price-symbol {
      font-size: 28rpx;
      color: #ff4d4f;
      font-weight: 500;
    }
    
    .price-value {
      font-size: 36rpx;
      color: #ff4d4f;
      font-weight: 500;
      margin-right: 15rpx;
    }
    
    .original-price {
      font-size: 26rpx;
      color: #999;
      text-decoration: line-through;
      margin-right: 20rpx;
    }
    
    .views-count {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  // 新增：热力值相关样式
  .product-heat {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    padding: 15rpx;
    background-color: #f9f9f9;
    border-radius: 8rpx;
    
    .heat-value {
      display: flex;
      align-items: center;
      
      .heat-text {
        font-size: 28rpx;
        color: #333;
        margin-left: 10rpx;
      }
	  .heat-tooltip {
	    margin-left: 10rpx;
	      cursor: pointer;  // 提示可点击
	    }    
    }
    
    .recharge-btn {
      background-color: #1677FF;
      color: #fff;
      font-size: 26rpx;
      padding: 10rpx 25rpx;
      border-radius: 6rpx;
      border: none;
    }
  }
  
  .product-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 15rpx;
    margin-bottom: 20rpx;
    
    .tag {
      color: #fff;
      font-size: 24rpx;
      padding: 5rpx 15rpx;
      border-radius: 4rpx;
    }
  }
  
  .product-stock {
    font-size: 26rpx;
    color: #666;
  }
}
/* 新增：充值弹框样式 */
.recharge-modal-content {
  padding: 20rpx 0;
  
  .recharge-desc {
    display: block;
    font-size: 26rpx;
    color: #666;
    margin-bottom: 20rpx;
    text-align: left;
  }
  
  .recharge-input {
    width: 100%;
    height: 80rpx;
    border: 1px solid #eee;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    margin-bottom: 15rpx;
    box-sizing: border-box;
  }
  
  .points-info {
    font-size: 24rpx;
    color: #999;
    text-align: left;
  }
}
// 详情页标签导航
.detail-tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    
    &.active {
      color: #1677FF;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 20%;
        width: 60%;
        height: 4rpx;
        background-color: #1677FF;
        border-radius: 2rpx;
      }
    }
  }
}

// 详情内容区域
.detail-content {
  height: calc(100vh - 500rpx - 300rpx); // 计算高度，确保可以滚动
  
  .detail-section,
  .parameters-section,
  .seller-section {
    background-color: #fff;
    padding: 20rpx;
    margin-bottom: 15rpx;
  }
  
  .detail-desc {
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
    margin-bottom: 20rpx;
  }
  
  .detail-img {
    width: 100%;
    margin-bottom: 10rpx;
  }
  
  .param-item {
    display: flex;
    padding: 15rpx 0;
    border-bottom: 1px solid #eee;
    
    &:last-child {
      border-bottom: none;
    }
    
    .param-name {
      flex: 0 0 200rpx;
      font-size: 26rpx;
      color: #666;
    }
    
    .param-value {
      flex: 1;
      font-size: 26rpx;
      color: #333;
    }
  }
  
  .seller-header {
    display: flex;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1px solid #eee;
    margin-bottom: 20rpx;
    
    .seller-avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }
    
    .seller-info {
      flex: 1;
      
      .seller-name {
        font-size: 30rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .seller-rating {
        display: flex;
        align-items: center;
        
        .stars {
          display: flex;
          
          .empty {
            color: #ddd !important;
          }
        }
        
        .rating-text {
          font-size: 24rpx;
          color: #666;
          margin-left: 10rpx;
        }
      }
    }
    
    .contact-btn {
      background-color: #1677FF;
      color: #fff;
      font-size: 26rpx;
      padding: 10rpx 25rpx;
      border-radius: 6rpx;
      border: none;
      display: flex;
      align-items: center;
      gap: 8rpx;
    }
  }
  
  .seller-contact {
    margin-bottom: 20rpx;
    
    .contact-item {
      display: flex;
      padding: 10rpx 0;
      
      .contact-label {
        flex: 0 0 150rpx;
        font-size: 26rpx;
        color: #666;
      }
      
      .contact-value {
        flex: 1;
        font-size: 26rpx;
        color: #333;
      }
    }
  }
  
  .seller-goods-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
    font-weight: 500;
  }
  
  .other-goods {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15rpx;
  }
  
  .other-good {
    background-color: #f9f9f9;
    border-radius: 8rpx;
    overflow: hidden;
    
    .other-good-img {
      width: 100%;
      height: 180rpx;
    }
    
    .other-good-name {
      font-size: 24rpx;
      color: #333;
      padding: 10rpx;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      height: 70rpx;
    }
    
    .other-good-price {
      font-size: 26rpx;
      color: #ff4d4f;
      padding: 0 10rpx 10rpx;
    }
  }
}
</style>
    